package org.victoria.market.utils;

import org.springframework.stereotype.Component;
import org.victoria.market.dao.DaoSupport;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2014/12/21.
 */
public class QueryHelper {

    private DaoSupport daoSupport;
    private Object value;
    private String namespace;
    private Map<String, Object> params;

    public QueryHelper(DaoSupport daoSupport) {
        this.daoSupport = daoSupport;
    }

    /**
     * clear last data
     */
    public void clear(){
        value = null;
        namespace = null;
        if (params!=null)
            params.clear();
    }

    /**
     * if set the value
     * @return
     */
    public boolean hasValue(){
        return value !=null || (params !=null && params.size()>0);
    }

    /**
     * set namespace that is corresponded with mybatis mapper
     * @param namespace namespace
     * @return
     */
    public QueryHelper setNameSpace(String namespace){
        this.namespace = namespace;
        return this;
    }

    /**
     * set value under the condition of single value
     * @param value single value
     */
    public QueryHelper setValue(Object value) {
        this.value = value;
        return this;
    }

    /**
     * put value in a map collection under the condition of multipart value
     * @param key key value
     * @param value value
     */
    public QueryHelper putValue(String key, Object value){
        if (params == null){
            params = new HashMap<String, Object>();
        }
        params.put(key, value);
        return this;
    }

    public Object getValue(){
        return params == null || params.size()==0 ? value : params;
    }

    /**
     * a certain namespace's format like [table name].[action name]
     * @return
     */
    public String getNamespace(){
        return namespace;
    }

    public DaoSupport dao(){
        return daoSupport;
    }
}
